package controllers

import command.CommandExec
import dao._
import implicits.BlastTool
import implicits.Implicits._
import org.apache.commons.io.FileUtils
import play.api.cache.AsyncCacheApi
import play.api.libs.json.Json
import play.api.mvc._
import tool.Pojo.CommandData
import tool.{FormTool, Tool}
import utils.Utils

import java.io.File
import javax.inject.Inject
import scala.concurrent.ExecutionContext.Implicits.global
import upickle.default._

/**
 * Created by yz on 16/9/2021
 */
class ToolController @Inject()(cc: ControllerComponents, cache: AsyncCacheApi)(
                                implicit val basicDao: BasicDao,
                                implicit val modeDao: ModeDao
) extends AbstractController(cc) {

  def downloadExampleData = Action {
    implicit request =>
      val data = FormTool.fileNameForm.bindFromRequest().get
      val resultFile = new File(Tool.exampleDir, data.fileName)
      Ok.sendFile(resultFile).withHeaders(
        CONTENT_DISPOSITION -> s"attachment; filename=${
          resultFile.getName
        }",
        CONTENT_TYPE -> "application/x-download"
      )
  }

  def getFileData = Action { implicit request =>
    val data = FormTool.fileNameForm.bindFromRequest().get
    val file = new File(Tool.dataDir, data.fileName)
    val (map, array) = Utils.getInfoByLines(file.txtLines)
    val json = Json.obj("map" -> map, "array" -> array)
    Ok(json)
  }

  def getXlsxFileData = Action { implicit request =>
    val data = FormTool.fileNameForm.bindFromRequest().get
    val file = new File(Tool.dataDir, data.fileName)
    val (map, array) = file.info
    val json = ujson.Obj("map" -> writeJs(map), "array" -> writeJs(array))
    Ok(json)
  }

  def getExampleText = Action { implicit request =>
    val data = FormTool.fileNameForm.bindFromRequest().get
    val file = new File(Tool.path, s"example/${data.fileName}")
    val str = FileUtils.readFileToString(file)
    Ok(str)
  }

  def openLiterPdf(fileName:String) = Action { implicit request =>
    val pdfFile=new File(Tool.refDir,s"${fileName}")
    val bytes=FileUtils.readFileToByteArray(pdfFile)
    Ok(bytes).as("application/pdf")
  }

}
